package com.example.server.manage.gptdialogue.controller;


import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.lang.Dict;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.HttpResponse;
import com.example.server.config.error.ErrorException;
import com.example.server.manage.gptdialogue.model.dto.ChatGptDTO;
import com.example.server.manage.gptdialogue.server.ChatGptService;
import com.example.server.manage.gptdialogue.server.ChatGptSseService;
import com.example.server.result.Result;
import com.fasterxml.jackson.databind.node.TextNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * chatGpt 对话请求
 *
 * <p>
 * ::本代码由[兮家小二]提供的代码生成器生成,如有问题,请手动修改 ::作者CSDN:https://blog.csdn.net/qq_41463655
 * </p>
 *
 * @author ws
 * @email 1720696548@qq.com
 * @date 2022-04-25 18:08:22
 */
@RestController
@RequestMapping("/gpt")
@Slf4j
public class ChatGptController {

    @Autowired
    private ChatGptService chatGptService;

    @Autowired
    private ChatGptSseService chatGptSseService;

    /**
     * 接口式 对话
     * @param dto
     * @return
     */
    @PostMapping(value = "/chat")
    @CrossOrigin
    public Result<ChatResponse> chat(@RequestBody ChatGptDTO dto) {
        try {
            return Result.success(chatGptService.chat(dto.getContent(), dto.getModel(), dto.getMaxTokens(), dto.getTemperature()));
        } catch (ResourceNotFoundException e) {
            String localizedMessage = e.getLocalizedMessage();
            return Result.error(9005, localizedMessage);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ErrorException("请求 openai 遇到点问题");
        }
    }

    /**
     * 流式对话
     * @param dto 请求参数
     * @return
     */
    @GetMapping(value = "/chat/sse")
    @CrossOrigin
    public  Flux<Dict> chatSse(HttpServletResponse response, @ModelAttribute ChatGptDTO dto) {
        response.addHeader("Content-Type", "text/event-stream");
        try {
            return chatGptSseService.chat(dto.getContent(), dto.getModel(), dto.getMaxTokens(), dto.getTemperature());
        } catch (IORuntimeException e) {
            throw new ErrorException("请求 openai 遇到点网络问题 IORuntimeException");
        }
    }
}
